import os
from celery import Celery
from celery.schedules import crontab
from hosts.models import Host, HostStat
from datetime import date

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'host_management.settings')
app = Celery('host_management')
app.config_from_object('django.conf:settings',namespace='CELERY')
app.autodiscover_tasks()

@app.task
def daily_host_stat():
    from django.db.models import Count
    stats = Host.objects.values('data_center__city', 'data_center').annotate(
        count=Count('id')
    )
    for stat in stats:
        HostStat.objects.create(
            city_id=stat['data_center__city'],
            data_center_id=stat['data_center'],
            host_count=stat['count'],
            stat_date=date.today()
        )

app.conf.beat_schedule = {
    'daily-host-stat': {
        'task': 'host_management.celery.daily_host_stat',
        'schedule': crontab(minute=0, hour=0),
    },
}